package com.example.myapplication;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.SearchView;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.floatingactionbutton.FloatingActionButton;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class ProductListFragment extends Fragment {

    private RecyclerView recyclerView;
    private ProductAdapterMain productAdapter;
    private SearchView searchView;
    private FloatingActionButton fabAddProduct;
    private DBHelper dbHelper;
    private SharedPreferences sharedPreferences;
    private ListView lvSearchHistory;
    private ArrayAdapter<String> historyAdapter;
    private List<String> searchHistory;

    private static final String PREFS_NAME = "SearchHistory";
    private static final String KEY_HISTORY = "history";

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_product_list, container, false);

        // 初始化组件
        recyclerView = view.findViewById(R.id.recyclerViewProducts);
        searchView = view.findViewById(R.id.searchViewProducts);
        fabAddProduct = view.findViewById(R.id.fabAddProduct);
        lvSearchHistory = view.findViewById(R.id.lvSearchHistory);

        dbHelper = new DBHelper(getContext());
        sharedPreferences = requireContext().getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);

        // 设置RecyclerView
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        loadProducts("");

        // 初始化搜索历史
        searchHistory = loadSearchHistoryWithPrefix(); // 加载搜索历史并添加前缀
        historyAdapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1, searchHistory);
        lvSearchHistory.setAdapter(historyAdapter);

        // 显示搜索历史
        lvSearchHistory.setOnItemClickListener((parent, view1, position, id) -> {
            String selectedHistory = searchHistory.get(position).replace("搜索历史：", ""); // 去掉前缀
            searchView.setQuery(selectedHistory, true);
        });

        // 搜索功能
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                saveSearchHistory(query); // 保存搜索历史
                loadProducts(query);
                refreshSearchHistory(); // 刷新历史
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                saveSearchHistory(newText); // 保存搜索历史
                loadProducts(newText);
                refreshSearchHistory(); // 刷新历史
                return true;
            }
        });

        // 添加商品按钮
        fabAddProduct.setOnClickListener(v -> {
            // 跳转到商品发布页面
            Intent intent = new Intent(getContext(), AddProductActivity.class);
            startActivity(intent);
        });

        return view;
    }


    public void filter(String query) {

        saveSearchHistory(query); // 保存搜索历史
        loadProducts(query);
        refreshSearchHistory(); // 刷新历史
    }

    @SuppressLint("Range")
    private void loadProducts(String keyword) {
        List<Product> productList = new ArrayList<>();
        Cursor cursor = dbHelper.getReadableDatabase().rawQuery(
                "SELECT * FROM products WHERE name LIKE ? OR description LIKE ?",
                new String[]{"%" + keyword + "%", "%" + keyword + "%"}
        );

        if (cursor.moveToFirst()) {
            do {
                Product product = new Product();
                product.setId(cursor.getInt(cursor.getColumnIndex("product_id")));
                product.setName(cursor.getString(cursor.getColumnIndex("name")));
                product.setDescription(cursor.getString(cursor.getColumnIndex("description")));
                product.setPrice(cursor.getDouble(cursor.getColumnIndex("price")));
                product.setImagePath(cursor.getString(cursor.getColumnIndex("image_path")));
                productList.add(product);
            } while (cursor.moveToNext());
        }
        cursor.close();

        productAdapter = new ProductAdapterMain(productList, getContext());
        recyclerView.setAdapter(productAdapter);
    }

    // 保存搜索历史
    private void saveSearchHistory(String query) {
        Set<String> historySet = sharedPreferences.getStringSet(KEY_HISTORY, new HashSet<>());
        List<String> historyList = new ArrayList<>(historySet);

        // 确保记录没有重复
        historyList.remove(query);
        historyList.add(query); // 添加到最后一个位置

        System.out.println("搜索历史：" + historyList);

        // 保存到 SharedPreferences
        sharedPreferences.edit()
                .putStringSet(KEY_HISTORY, new HashSet<>(historyList))
                .apply();
    }

    // 获取最后一个搜索结果
    private String getLastSearchResult() {
        Set<String> historySet = sharedPreferences.getStringSet(KEY_HISTORY, new HashSet<>());
        List<String> historyList = new ArrayList<>(historySet);

        // 如果历史为空，返回默认值
        if (historyList.isEmpty()) {
            return "搜索历史：默认搜索";
        }

        // 返回最后一个结果
        return "搜索历史：" + historyList.get(historyList.size() - 1);
    }

    // 加载搜索历史并添加前缀
    private List<String> loadSearchHistoryWithPrefix() {
        Set<String> historySet = sharedPreferences.getStringSet(KEY_HISTORY, new HashSet<>());
        List<String> historyList = new ArrayList<>();
        for (String item : historySet) {
            if (!item.isEmpty()) {
                historyList.add("搜索历史：" + item); // 添加前缀
            }
        }
        return historyList;
    }

    // 刷新搜索历史列表
    private void refreshSearchHistory() {
        searchHistory.clear();
        searchHistory.addAll(loadSearchHistoryWithPrefix());
        historyAdapter.notifyDataSetChanged();
    }
}
